package com.itheima.service.impl;

import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> select() {
        List<Category> categories = categoryMapper.all();
        if (CollectionUtils.isEmpty(categories)) {
            return Collections.emptyList();
        }
        List<Category> parens = categories.stream().filter(c -> c.getParentId() == 0).toList();
        List<Category> children = categories.stream().filter(c -> c.getParentId() != 0).toList();
        parens.forEach(p -> findChildren(p, children));
        return parens;
    }


    public void findChildren(Category category, List<Category> categoryList) {
        List<Category> list = categoryList.stream().filter(c -> Objects.equals(category.getId(), c.getParentId())).toList();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(c -> findChildren(c,categoryList));
        }
        category.setChidren(list);
    }
}
